package controller;

import modle.Bean.JDBCUtil;
import modle.Bean.User;
import modle.DAO.UserDao;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serial;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/DeleteUser")
public class DeleteUserServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 6L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        JDBCUtil db = new JDBCUtil();
        Connection conn = db.getConn();
        response.setContentType("text/javascript;charset=UTF-8");
        UserDao userDao = new UserDao();
        try {
            userDao.deleteUser(conn,username);
            // 将userList数据转换为json格式数据
            Map<String, Object> result = new HashMap<>();
            List<User> userList = userDao.getAllUsers(conn);  // 获取所有用户数据
            result.put("code", 0);
            result.put("msg", "请求成功");
            result.put("count", userList.size());
            result.put("data", userList);
            JSONObject json = new JSONObject(result);
            String jsonStr = json.toString();
            try (PrintWriter out = response.getWriter()) {
                out.write(jsonStr);
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {

            throw new RuntimeException(e);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
